<?php
namespace app\faxing\channel;


use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class San60 extends FaXingBase
{

    public function register($params)
    {
        $cid = $this->cid;
        // md5(qid=278479758&time=1763969931&server_id=S1UXPRjgBRFxAJTao7P8XFo338oDRht003)
        $sign_data = [
            'qid' => $params['qid'],
            'time' => $params['time'],
            'server_id' => $params['server_id'],
            'sign' => $params['sign'],
        ];
        if(!$this->check_sign($sign_data,$this->extdata['LKEY'])){
            echo 0;exit;
        }

        $account = $cid."_".$params['qid'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            $data['is_age'] = 0;
            if($params['isAdult'] == 1){
                $data['is_age'] = 2;
            }
            if($params['isAdult'] == 0){
                $data['is_age'] = 1;
            }

            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        $player['third_data'] = $params;
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];
    }


    public function order($order)
    {
        $role = PlayerRole::where(['gid'=>$order['gid'],'uid'=>$order['uid'],'cid'=>$order['cid']])->find();
        $token = get_encrypt($order['uid']);

        $redis = new Redis();
        $player = $redis->get($token);

        $third_data = $player['third_data'];

        $account = $player['account'];
        $account = explode("_",$account);
        $sign = get_sign(['order_no'=>$order['order_no']],$this->extdata['PKEY']); // 回传验证
        $time = time();
        $data = [
            'uid' => $account[1],
            'platform' =>'wan',
            'gkey' =>$this->extdata['gameid'],
            'skey'=>'S1',//区服id
            'amount'=> $order['amount'] * 100,//金额 整数：分
            'rid' => $role['role_id'],
            'pid'=>rand(000000,999999),//商品id
            'exts_cp'=> $order['order_no']."|".$sign, // 回传验证
        ];
        //$sign=md5($uid.$gkey.$skey.$amount.$rid.$pid.$ext_cp.$key)；
        $data['sign'] = md5($data['uid'].$data['gkey'].$data['skey'].$data['amount'].$data['rid'].
            $data['pid'].$data['exts_cp'].$this->extdata['PKEY']);
        $url = "https://iap.g.360-api.cn/mini.html?";
        return $url.urldecode(http_build_query($data));
    }

    public function check_order($params)
    {
        $ord_arr = explode("|",$params['exts']);
        $order_no = $ord_arr[0];
        $sign = $ord_arr[1];

        // 双重校验
        $order_sign = get_sign(['order_no'=>$order_no],$this->extdata['APPKEY']);

        if($order_sign != $sign){
            echo json_encode(['code'=>403,'message'=>'签名错误']);exit;
        }

        // 查询订单
        $order = Order::where([
            'order_no'=>$order_no
        ])->find();

        if(!$this->check_sign($params,$this->extdata['P_key'])){
            echo json_encode(['code'=>403,'message'=>'签名错误']);exit;
        }

        if($order['amount'] != $params['Money']){
            echo json_encode(['code'=>500,'message'=>'处理失败']);exit;
        }

        $order->trade_no = $params['OrderNo'];
        $order->save();

        return $order;
    }

    public function getRole($params)
    {
        $uid = get_channel_player_by_account($params['qid'],$this->cid);

        if(!$uid){
            echo 0;exit;
        }
        $role = PlayerRole::where(['gid'=>$this->gid,'uid'=>$uid,'cid'=>$this->cid])->find();
        if(empty($role)){
            echo 0;exit;
        }else{
            echo 1;exit;
        }

        echo json_encode(['code'=>0,'data'=>$data,'message'=>"查询成功"]);exit;
    }


    public function message($message,$order)
    {
        echo $message === 'success' ? json_encode(['code'=>0,'message'=>'充值成功']) :  json_encode(['code'=>500,'message'=>'处理失败']);
        exit;
    }

    private function signData($data, $secret) {
//        ksort($data);
        foreach ($data as $k => $v) {
            $tmp[] = $k . '=' . urlencode($v);
        }
        $str = implode('&', $tmp) . $secret;

        return md5($str);
    }
    protected function check_sign($params, $key)
    {
        $sign_data = $params;
        unset($sign_data['cid']);
        unset($sign_data['gid']);
        $sign = $sign_data['sign'];
        unset($sign_data['sign']);

        $check_sign = $this->signData($sign_data,$key);

        if($check_sign != $sign){
            return false;
        }
        return true;
    }

}